#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from confignb import ConfigNB
from conectionnb import ConectionNB
from ftpd import Ftpd
from blockpcd import BlockPCD
import threading
import time
from actionsnb import ActionsNB

class MonitoringNB(threading.Thread):
	def __init__(self):
		try:
			threading.Thread.__init__(self, name = "monitoring")
			self.__config = ConfigNB()
			self.__service = ConectionNB()
			self.__actions = ActionsNB()
			self.__ftpd = Ftpd()
			self.__pcblockd = BlockPCD()
		except:
			print "Problemas al iniciar el monitoreo"
			
	def run(self): #Loop principal
		print "Iniciando servicios de monitoreo..."
		self.__actions.connectToWifi()
		self.__service.requestData()
		
		print "Monitorizando..."
		while True:
			self.__comprovarServidores()
			time_ciclo = self.__config.getTimeSendData()
			time.sleep(60.0 * float(time_ciclo))
	
	def __comprovarServidores(self):
		self.__actions.connectToWifi()
		self.__service.requestData()
		print "Configuración cargada satisfactoriamente"
		perdido = self.__config.isDevicePerdido()
		if perdido:
			if self.__config.isKillProc():
				self.__actions.matarProceso(self.__config.getProcessNameKill())
			if self.__config.isPcBloqueadoConfig():
				if not self.__pcblockd.isAlive():
					self.__pcblockd = BlockPCD()
					self.__pcblockd.blockPc()
			elif self.__pcblockd.isAlive():
				self.__pcblockd.desblockPc()
			if self.__config.isFtpServiceRun():
				if not self.__ftpd.isAlive():
					self.__ftpd = Ftpd()
					self.__ftpd.start()
			elif self.__ftpd.isAlive():
				self.__ftpd.stop()
			if self.__config.isAlertActive() and not self.__config.isPcBloqueadoConfig():
				self.__actions.mostrarMensaje(self.__config.getMsgAlert())		
			self.__service.sendData()
		else:
			if self.__pcblockd.isAlive():
				self.__pcblockd.desblockPc()
			elif self.__ftpd.isAlive():
				self.__ftpd.stop()
			